import Taro from "@tarojs/taro";

//防抖
let timer;

export function debounce(func, ms = 1000) {
  return function f(...args) {
    if (timer) {
      clearTimeout(timer)
    }
    timer = setTimeout(() => {
      func.apply(this, args)
    }, ms)
  }
}

export const showInternalError = debounce((msg) => {
  if (!msg) {
    Taro.showModal({
      title: '网络繁忙',
      content: '请稍后重试',
      showCancel: false,
      confirmText: '好的'
    });
    return;
  }
  // const showQRCodeEntry = !!msg.showPersonalQRCodeEntry;
  const showQRCodeEntry = false;
  const errorCode = msg.errorCode ? '，错误码:' + msg.errorCode : '';
  let content = (msg.content ? msg.content : '请稍后重试') + errorCode;
  let showCancel = showQRCodeEntry;
  const cancelText = '关闭';
  const confirmText = showQRCodeEntry ? '个人码' : '关闭';
  Taro.showModal({
    title: msg.title || '提示',
    content,
    showCancel,
    cancelText,
    confirmText,
    success(res) {
      if (res.confirm && showQRCodeEntry) {
        Taro.navigateTo({
          url: '/pkg_me/customer_qrcode/customer_qrcode'
        });
      }
    }
  })
})

export const showInternalErrorV2 = debounce((msg?: {
  title?: string,
  content?: string,
  confirmText?: string,
}) => {
  console.log(msg)
  const _msg = {
    title: '提示',
    content: '网络繁忙，请稍后重试',
    confirmText: '关闭',
    ...msg,
  }
  Taro.showModal({
    title: _msg.title,
    content: _msg.content,
    showCancel: false,
    confirmText: _msg.confirmText,
  })
})

export const showAccessTokenExpired = () => {
  Taro.showModal({
    title: '身份认证过期',
    content: '请重新进入小程序',
    showCancel: false,
    confirmText: '好的'
  })
}

export const showAccessTokenExpiredV2 = () => {
  Taro.showModal({
    title: '身份认证过期',
    content: '请重新进入小程序',
    showCancel: false,
    confirmText: '好的'
  })
}

/**
 * 业务错误Modal提示
 * @param options
 * @return false
 */
export const showBusinessErrorModal = (options: { title?: string, content?: string }): boolean => {
  Taro.hideLoading();
  Taro.hideToast();
  Taro.showModal({
    title: options.title || '出错了',
    content: options.content || '未知错误',
    showCancel: false,
    confirmText: '好的'
  })
  return false;
}

/**
 * 业务成功Toast提示
 * @param title
 * @return true
 */
export const showBusinessSuccessToast = (title?: string): boolean => {
  Taro.hideLoading();
  Taro.hideToast();
  Taro.showToast({
    title: title || '成功',
    icon: 'success'
  })
  return true;
}
